import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import Taro from '@tarojs/taro';
import { login as loginAPI, register as registerAPI, getUserInfo as getUserInfoAPI, updateUserInfo as updateUserInfoAPI, updatePhoto as updatePhotoAPI, updateIntroduce as updateIntroduceAPI } from '../services/api';
import { storage, ui } from '../utils/platform';

// 获取本地存储的安全函数
const getStorage = (key) => {
  try {
    return storage.getSync(key);
  } catch (e) {
    console.error('获取存储失败:', e);
    return null;
  }
};

// 设置本地存储的安全函数
const setStorage = (key, data) => {
  try {
    storage.setSync(key, data);
  } catch (e) {
    console.error('设置存储失败:', e);
  }
};

// 移除本地存储的安全函数
const removeStorage = (key) => {
  try {
    storage.removeSync(key);
  } catch (e) {
    console.error('移除存储失败:', e);
  }
};

// 创建异步action: 登录
export const loginUser = createAsyncThunk(
  'auth/login',
  async ({ name, password }, { rejectWithValue }) => {
    try {
      const response = await loginAPI(name, password);
      
      if (response && response.token) {
        // 存储token和用户信息
        setStorage('token', response.token);
        setStorage('userInfo', response.userInfo || { name });
        return response;
      } else {
        return rejectWithValue('登录失败，请重试');
      }
    } catch (error) {
      return rejectWithValue(error.message || '登录失败，请重试');
    }
  }
);

// 创建异步action: 注册
export const registerUser = createAsyncThunk(
  'auth/register',
  async ({ name, password }, { rejectWithValue }) => {
    try {
      // 注册前清除任何现有的token，避免冲突
      removeStorage('token');
      removeStorage('userInfo');
      
      const response = await registerAPI(name, password);
      console.log('注册API响应:', response);
      return response;
    } catch (error) {
      console.error('注册API错误:', error);
      // 传递完整的错误信息，包括状态码和详细信息
      const errorInfo = {
        message: error.message || '注册失败，请重试',
        status: error.status,
        data: error.data
      };
      return rejectWithValue(errorInfo);
    }
  }
);

// 创建异步action: 获取用户详细信息
export const fetchUserInfo = createAsyncThunk(
  'auth/fetchUserInfo',
  async (_, { rejectWithValue, getState }) => {
    try {
      // 确保有有效的token
      const state = getState();
      const token = state.auth.token || getStorage('token');
      
      if (!token) {
        return rejectWithValue('未找到有效的认证令牌');
      }
      
      console.log('fetchUserInfo: 使用token:', token);
      const userInfo = await getUserInfoAPI();
      if (userInfo) {
        // 保留当前的 loginType，避免被覆盖
        const currentUserInfo = state.auth.userInfo;
        const updatedUserInfo = {
          ...userInfo,
          loginType: currentUserInfo?.loginType || userInfo.loginType
        };
        // 更新本地存储的用户信息
        setStorage('userInfo', updatedUserInfo);
        return updatedUserInfo;
      } else {
        return rejectWithValue('获取用户信息失败');
      }
    } catch (error) {
      console.error('fetchUserInfo错误:', error);
      return rejectWithValue(error.message || '获取用户信息失败');
    }
  }
);

// 创建异步action: 更新用户头像
export const updatePhoto = createAsyncThunk(
  'auth/updatePhoto',
  async (photoPath, { rejectWithValue }) => {
    try {
      const result = await updatePhotoAPI(photoPath);
      
      if (result && !result.error) {
        return { success: true, data: result };
      } else {
        return rejectWithValue(result.error || '更新头像失败');
      }
    } catch (error) {
      console.error('更新头像失败:', error);
      return rejectWithValue(error.message || '更新头像失败');
    }
  }
);

// 创建异步action: 更新用户简介
export const updateIntroduce = createAsyncThunk(
  'auth/updateIntroduce',
  async (introduce, { rejectWithValue }) => {
    try {
      const safeIntroduce = introduce || '';
      const result = await updateIntroduceAPI(safeIntroduce);
      
      if (result && !result.error) {
        return { success: true, data: result };
      } else {
        return rejectWithValue(result.error || '更新简介失败');
      }
    } catch (error) {
      console.error('更新简介失败:', error);
      return rejectWithValue(error.message || '更新简介失败');
    }
  }
);

// 创建异步action: 更新用户基本信息（兼容旧版本）
export const updateUserInfo = createAsyncThunk(
  'auth/updateUserInfo',
  async ({ introduce, photoPath }, { rejectWithValue }) => {
    try {
      // 确保introduce不为undefined或null
      const safeIntroduce = introduce || '';
      
      const result = await updateUserInfoAPI(safeIntroduce, photoPath);
      
      if (result && !result.error) {
        // 更新成功返回结果
        return { success: true, data: result };
      } else {
        return rejectWithValue(result.error || '更新用户信息失败');
      }
    } catch (error) {
      console.error('更新用户信息失败:', error);
      return rejectWithValue(error.message || '更新用户信息失败');
    }
  }
);

// 创建异步action: 微信登录
export const wechatLogin = createAsyncThunk(
  'auth/wechatLogin',
  async (code, { rejectWithValue, dispatch }) => {
    try {
      const response = await Taro.request({
        url: `https://www.yzyt.xyz/auth/wechat/login?code=${code}`,
        method: 'GET'
      });
      
      console.log('微信登录后端响应:', response.data);
      
      if (response.data && response.data.token) {
        const { token, openId, sessionKey, isOldUser } = response.data;
        
        // 存储微信相关信息
        setStorage('token', token);
        setStorage('openId', openId);
        setStorage('sessionKey', sessionKey);
        
        let userInfo = null;
        
        // 如果是老用户，尝试获取用户详细信息
        if (isOldUser === 1) {
          try {
            const userInfoResult = await getUserInfoAPI();
            if (userInfoResult && !userInfoResult.error) {
              userInfo = {
                ...userInfoResult,
                loginType: 'wechat' // 确保设置登录类型
              };
              setStorage('userInfo', userInfo);
            }
          } catch (error) {
            console.log('获取用户信息失败，但微信登录成功:', error);
            // 即使获取用户信息失败，也设置一个基本的用户信息
            userInfo = {
              name: '微信用户',
              loginType: 'wechat'
            };
            setStorage('userInfo', userInfo);
          }
        } else {
          // 新用户设置基本信息
          userInfo = {
            name: '微信用户',
            loginType: 'wechat'
          };
          setStorage('userInfo', userInfo);
        }
        
        return {
          token,
          openId,
          sessionKey,
          isOldUser,
          userInfo
        };
      } else {
        return rejectWithValue('微信登录失败，请重试');
      }
    } catch (error) {
      console.error('微信登录失败:', error);
      return rejectWithValue(error.message || '微信登录失败，请重试');
    }
  }
);

// 初始状态
const initialState = {
  userInfo: getStorage('userInfo') || null,
  token: getStorage('token') || null,
  isLoggedIn: !!getStorage('token'),
  isLoading: false,
  error: null
};

// 创建认证切片
const authSlice = createSlice({
  name: 'auth',
  initialState,
  reducers: {
    logout: (state) => {
      removeStorage('token');
      removeStorage('userInfo');
      
      state.token = null;
      state.userInfo = null;
      state.isLoggedIn = false;
      state.error = null;
      
      // 显示退出登录成功提示
      ui.showToast({
        title: '已退出登录',
        icon: 'success',
        duration: 2000
      });
      
      // 登出后跳转到登录页
      setTimeout(() => {
        ui.redirectTo({
          url: '/pages/login/index',
        });
      }, 1000);
    },
    clearError: (state) => {
      state.error = null;
    },
    checkLoginStatus: (state) => {
      const storedToken = getStorage('token');
      const storedUserInfo = getStorage('userInfo');

      if (storedToken) {
        state.token = storedToken;
        state.userInfo = storedUserInfo;
        state.isLoggedIn = true;
      }
    }
  },
  extraReducers: (builder) => {
    builder
      // 登录状态处理
      .addCase(loginUser.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(loginUser.fulfilled, (state, action) => {
        state.isLoading = false;
        state.token = action.payload.token;
        state.userInfo = action.payload.userInfo || { name: action.meta.arg.name };
        state.isLoggedIn = true;
      })
      .addCase(loginUser.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload;
      })
      // 注册状态处理
      .addCase(registerUser.pending, (state) => {
        state.isLoading = true;
        state.error = null;
        // 注册时清除现有的认证状态
        state.token = null;
        state.userInfo = null;
        state.isLoggedIn = false;
      })
      .addCase(registerUser.fulfilled, (state) => {
        state.isLoading = false;
        // 注册成功后保持未登录状态，等待后续登录
      })
      .addCase(registerUser.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload;
      })
      // 获取用户详细信息状态处理
      .addCase(fetchUserInfo.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(fetchUserInfo.fulfilled, (state, action) => {
        state.isLoading = false;
        state.userInfo = action.payload;
      })
      .addCase(fetchUserInfo.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload;
      })
      // 处理更新用户头像
      .addCase(updatePhoto.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(updatePhoto.fulfilled, (state) => {
        state.isLoading = false;
      })
      .addCase(updatePhoto.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload || '更新头像失败';
      })
      // 处理更新用户简介
      .addCase(updateIntroduce.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(updateIntroduce.fulfilled, (state) => {
        state.isLoading = false;
      })
      .addCase(updateIntroduce.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload || '更新简介失败';
      })
      // 处理更新用户信息（兼容模式）
      .addCase(updateUserInfo.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(updateUserInfo.fulfilled, (state) => {
        state.isLoading = false;
      })
      .addCase(updateUserInfo.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload || '更新用户信息失败';
      })
      // 处理微信登录
      .addCase(wechatLogin.pending, (state) => {
        state.isLoading = true;
        state.error = null;
      })
      .addCase(wechatLogin.fulfilled, (state, action) => {
        console.log('wechatLogin.fulfilled - payload:', action.payload);
        state.isLoading = false;
        state.token = action.payload.token;
        state.userInfo = action.payload.userInfo;
        state.isLoggedIn = true;
        console.log('wechatLogin.fulfilled - updated state:', {
          token: state.token,
          userInfo: state.userInfo,
          isLoggedIn: state.isLoggedIn
        });
      })
      .addCase(wechatLogin.rejected, (state, action) => {
        state.isLoading = false;
        state.error = action.payload;
      });
  }
});

// 导出actions
export const { logout, clearError, checkLoginStatus } = authSlice.actions;

// 导出selector
export const selectAuth = (state) => state.auth;
export const selectIsLoggedIn = (state) => state.auth.isLoggedIn;
export const selectUserInfo = (state) => state.auth.userInfo;
export const selectToken = (state) => state.auth.token;
export const selectIsLoading = (state) => state.auth.isLoading;
export const selectError = (state) => state.auth.error;

// 导出reducer
export default authSlice.reducer;